<template>
  <n-layout class="layout-wrapper">
    <n-layout-header bordered>
      <div class="header">
        <LogoTitle title="个人工作区"></LogoTitle>
        <n-space align="center" size="small">
          <!-- <n-select
            size="small"
            style="width: 90px"
            :options="i18nOptions"
            v-model:value="locale"
          ></n-select> -->
          <!-- <n-button circle quaternary>
            <template #icon>
              <n-icon size="18">
                <NotificationsOutline></NotificationsOutline>
              </n-icon>
            </template>
          </n-button> -->
          <messageBox></messageBox>
          <n-divider vertical></n-divider>
          <!-- <n-popselect
            :on-update:value="handleInfoSelect"
            trigger="click"
            :options="infoOptions"
          >
            <n-button quaternary circle>
              <template #icon>
                <n-icon size="18">
                  <InformationOutline></InformationOutline>
                </n-icon>
              </template>
            </n-button>
          </n-popselect> -->
          <themeSwitch></themeSwitch>
          <!-- <n-switch v-model:value="isDark" :on-update:value="toggleDark">
            <template #checked-icon>
              <n-icon :component="MoonOutline" />
            </template>
            <template #unchecked-icon>
              <n-icon :component="SunnyOutline" />
            </template>
          </n-switch> -->
          <n-divider vertical></n-divider>
          <userProfile></userProfile>
        </n-space>
      </div>
    </n-layout-header>

    <n-layout has-sider sider-placement="left">
      <n-layout-sider :width="150" bordered>
        <n-menu
          :collapsed-width="64"
          :collapsed-icon-size="22"
          :options="adminMenus"
          v-model:value="menuKey"
        />
      </n-layout-sider>
      <n-layout-content>
        <div style="display: flex; height: calc(100vh - 60px)">
          <n-layout v-if="userStore.userInfo.id != -1 && menuKey">
            <n-layout-content style="padding: 24px; height: 100%">
              <n-scrollbar style="height: 100%">
                <router-view></router-view>
              </n-scrollbar>
            </n-layout-content>
          </n-layout>
        </div>
      </n-layout-content>
    </n-layout>
  </n-layout>
  <!-- <feedback ></feedback> -->
  <DialogFormBuilder
    :schema="feedbackJson"
    ref="feedbackRef"
  ></DialogFormBuilder>
</template>

<script lang="ts" setup>
import LogoTitle from "@/components/logo-title/index.vue";
import userProfile from "@/components/login/user-profile.vue";
import themeSwitch from "@/components/theme-switch/index.vue";
import {
  HomeOutline,
  FolderOutline,
  SettingsOutline,
  InformationCircleOutline,
  NotificationsCircleOutline,
  NotificationsOutline,
  InformationOutline,
  SunnyOutline,
  CloudyNightOutline,
  MoonOutline,
  PersonOutline,
  DocumentTextOutline,
  BrowsersOutline,
  EarthSharp,
  RecordingOutline,
  ReceiptOutline,
} from "@vicons/ionicons5";
import { Component, h, ref, watch, onMounted, computed } from "vue";
import { NIcon } from "naive-ui";
import datasets from "./components/dataset.vue";
import files from "./components/files.vue";
import setting from "./components/setting.vue";
// import feedback from "./components/form/feedback.vue";
import DialogFormBuilder from "@/components/form-builder/dialog.vue";
import { useDark, useToggle } from "@vueuse/core";
import { useI18n } from "vue-i18n";
import feedbackJson from "./components/form/feedback.json";
import storageVue from "./components/storage/index.vue";
import { RouterLink, useRoute, useRouter } from "vue-router";
import { useUserStore } from "@/store/user";
import messageBox from "@/components/messageBox/index.vue";
const userStore = useUserStore();
const route = useRoute();
const isDark = useDark();
const toggleDark = useToggle(isDark);
const feedbackRef = ref();
const menuKey = ref("");
const router = useRouter();
const isShow = ref(false);
function renderIcon(icon: Component) {
  return () => h(NIcon, { size: 16 }, { default: () => h(icon) });
}
const { locale, t } = useI18n();
const changeLang = (parameter) => {
  const lang = parameter.target.value;
  locale.value = lang; // 切换语言
  localStorage.setItem("LANG", lang); // 本地存储当前语言类型
};
router.beforeEach((to, from, next) => {
  console.log(to, from, next);
  next();
});
// router.beforeRouteEnter (to, from, next) {
//   // ...
// }((e) => {
//   console.log("to", e);
// });
watch(
  () => locale.value,
  (val) => {
    localStorage.setItem("LANG", val);
    window.location.reload();
  }
);
const i18nOptions = [
  {
    label: "中文",
    value: "zh",
  },
  {
    label: "English",
    value: "en",
  },
];
const infoOptions = [
  {
    label: t("help"),
    value: 0,
  },
  {
    label: t("feedback"),
    value: 1,
  },
];
function hasComm(arr1, arr2) {
  for (let i = 0; i < arr1.length; i++) {
    if (arr2.includes(arr1[i])) {
      return true; // 找到共同元素，返回true
    }
  }
  return false; // 没有找到共同元素，返回false
}
const menus = ref([
  {
    label: () =>
      h(
        RouterLink,
        { to: { name: "form" } },
        { default: () => t("form_list") }
      ),
    roles: [1, 2],
    key: "form",
    icon: renderIcon(DocumentTextOutline),
  },
  {
    label: () =>
      h(
        RouterLink,
        { to: "department" },
        { default: () => t("department_manage") }
      ),
    roles: [1],
    key: "department",
    icon: renderIcon(EarthSharp),
  },
  {
    label: () =>
      h(
        RouterLink,
        { to: "personCenter" },
        { default: () => t("user-manage") }
      ),
    roles: [2],
    key: "personCenter",
    icon: renderIcon(PersonOutline),
  },
  {
    label: () =>
      h(RouterLink, { to: "setting" }, { default: () => t("setting") }),
    key: "setting",
    roles: [1],
    icon: renderIcon(SettingsOutline),
  },
  {
    label: () =>
      h(RouterLink, { to: "overview" }, { default: () => t("overview") }),
    key: "overview",
    icon: renderIcon(ReceiptOutline),
  },
  {
    label: () =>
      h(
        RouterLink,
        { to: "record-detail" },
        { default: () => t("record-detail") }
      ),
    key: "record-detail",
    roles: [3],
    icon: renderIcon(RecordingOutline),
  },
]);
const adminMenus = computed(() => {
  const res = [];
  for (let i = 0; i < menus.value.length; i++) {
    const menu = menus.value[i];
    if (hasComm(menu.roles || [], userStore.roles || [])) {
      res.push(menu);
    }
  }
  return res;
  // return menus.value.map(menu=>{
  //   return if()
  // })
});
const handleInfoSelect = (val: number) => {
  if (val == 1) {
    feedbackRef.value.open();
  }
};
onMounted(async () => {
  // const key = route.path.split("/")[2];
  // menuKey.value = key;
  await userStore.updateUserInfo();
  watch(
    () => route.path,
    (val) => {
      const key = route.path.split("/")[2];
      const selectMenu = menus.value.find((item) => item.key == key);
      if (selectMenu) {
        if (hasComm(selectMenu.roles || [], userStore.roles || [])) {
          // res.push(menu);

          menuKey.value = key;
        } else {
          menuKey.value = "";
          router.replace("/");
        }
      } else {
        // menuKey.value = "";
        // router.replace("/");
      }
      // const
    },
    {
      immediate: true,
    }
  );

  // console.log(userStore.roles);
});
</script>

<style lang="scss" scoped>
.header {
  width: 100%;
  box-sizing: border-box;
  padding: 8px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.layout-wrapper {
  height: 100vh;
}

:deep() {
  .n-menu-item-content-header {
    text-align: left !important;
  }
}
</style>
